package com.easyban.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.easyban.Dto.SessionShareDto;
import com.easyban.constants.Constants;
import com.easyban.entity.enums.ResponseCodeEnum;
import com.easyban.entity.enums.ShareValidTypeEnums;
import com.easyban.entity.po.FileInfo;
import com.easyban.exception.BusinessException;

import com.easyban.mappers.FileShareMapper;
import com.easyban.service.FileInfoService;
import com.easyban.utils.DateUtil;
import com.easyban.utils.RedisUtils;
import org.springframework.stereotype.Service;

import com.easyban.entity.enums.PageSize;
import com.easyban.entity.query.FileShareQuery;
import com.easyban.entity.po.FileShare;
import com.easyban.entity.vo.PaginationResultVO;
import com.easyban.entity.query.SimplePage;
import com.easyban.service.FileShareService;
import com.easyban.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 分享信息 业务接口实现
 */
@Service("fileShareService")
public class FileShareServiceImpl implements FileShareService {

	@Resource
	private FileShareMapper<FileShare, FileShareQuery> fileShareMapper;
	@Resource
	private RedisUtils redisUtils;
	@Resource
	private FileInfoService fileInfoService;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<FileShare> findListByParam(FileShareQuery param) {
		List<FileShare> fileShares = this.fileShareMapper.selectList(param);

		return fileShares;
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(FileShareQuery param) {
		return this.fileShareMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<FileShare> findListByPage(FileShareQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<FileShare> list = this.findListByParam(param);
		PaginationResultVO<FileShare> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(FileShare bean) {
		return this.fileShareMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<FileShare> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.fileShareMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<FileShare> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.fileShareMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(FileShare bean, FileShareQuery param) {
		StringTools.checkParam(param);
		return this.fileShareMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(FileShareQuery param) {
		StringTools.checkParam(param);
		return this.fileShareMapper.deleteByParam(param);
	}

	/**
	 * 根据ShareId获取对象
	 */
	@Override
	public FileShare getFileShareByShareId(String shareId) {
		return this.fileShareMapper.selectByShareId(shareId);

	}

	/**
	 * 根据ShareId修改
	 */
	@Override
	public Integer updateFileShareByShareId(FileShare bean, String shareId) {
		return this.fileShareMapper.updateByShareId(bean, shareId);
	}

	/**
	 * 根据ShareId删除
	 */
	@Override
	public Integer deleteFileShareByShareId(String shareId) {
		return this.fileShareMapper.deleteByShareId(shareId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveShare(FileShare share) {
		ShareValidTypeEnums typeEnum = ShareValidTypeEnums.getByType(share.getValidType());

		if (null == typeEnum) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		if (typeEnum != ShareValidTypeEnums.FOREVER) {
			share.setExpireTime(DateUtil.getAfterDAte(typeEnum.getDays()));
		}
		Date curDate = new Date();
		share.setShareTime(curDate);
		if (StringTools.isEmpty(share.getCode())) {
			share.setCode(StringTools.getRandomString(Constants.LENGTH_5));
		}
		share.setShareId(StringTools.getRandomString(Constants.LENGTH_20));
		if (typeEnum.getDays()!=-1) {
			redisUtils.cacheValue(Constants.SESSION_SHARE_KEY + share.getShareId(), share, typeEnum.getDays() * Constants.READIS_TIME_share);

		}else {
			redisUtils.cacheValue(Constants.SESSION_SHARE_KEY + share.getShareId(), share);
		}
		this.fileShareMapper.insert(share);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteFileShareBatch(String[] shareIdArray, String userId) {
		Integer count = this.fileShareMapper.deleteFileShareBatch(shareIdArray, userId);
		if (count != shareIdArray.length) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public SessionShareDto checkShareCode(String shareId, String code) {
		FileShare share = this.fileShareMapper.selectByShareId(shareId);
		if (null == share || (share.getExpireTime() != null && new Date().after(share.getExpireTime()))) {
			throw new BusinessException(ResponseCodeEnum.CODE_902);
		}
		if (!share.getCode().equals(code)) {
			throw new BusinessException("提取码错误");
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		/*如果验证通过，就存session，下次就不用输入了*/
		session.setAttribute(Constants.SESSION_KEY+shareId,shareId);
		/*//更新浏览次数*/
		this.fileShareMapper.updateShareShowCount(shareId);
		SessionShareDto shareSessionDto = new SessionShareDto();
		shareSessionDto.setShareId(shareId);
		shareSessionDto.setShareUserId(share.getUserId());
		shareSessionDto.setFileId(share.getFileId());
		shareSessionDto.setExpireTime(share.getExpireTime());
		return shareSessionDto;
	}
}